package com.aisile.sellergoods.service.impl;

import com.aisile.entity.PageResult;
import com.aisile.mapper.TbSpecificationOptionMapper;
import com.aisile.mapper.TbTypeTemplateMapper;
import com.aisile.pojo.TbSpecificationOption;
import com.aisile.pojo.TbSpecificationOptionExample;
import com.aisile.pojo.TbTypeTemplate;
import com.aisile.pojo.TbTypeTemplateExample;
import com.aisile.sellergoods.service.TypeTemplateService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @标题 TypeTemplateServiceImpl
 * @作者 Mr.chen
 * @创建日期 2018/12/28 16:19
 * @版本号 1.0
 **/
@Service
public class TypeTemplateServiceImpl implements TypeTemplateService {
    @Autowired
    TbTypeTemplateMapper tbTypeTemplateMapper;

    @Override
    public PageResult findPage(int page, int rows, TbTypeTemplate tbTypeTemplate) {
        PageHelper.startPage(page,rows);
        String name = tbTypeTemplate.getName();
        TbTypeTemplateExample example = new TbTypeTemplateExample();
        if(!StringUtils.isEmpty(name)){
            example.createCriteria().andNameLike("%"+name+"%");
        }
        Page<TbTypeTemplate> pageModel =  (Page<TbTypeTemplate>)tbTypeTemplateMapper.selectByExample(example);
        return new PageResult(pageModel.getTotal(),pageModel.getResult());
    }

    @Override
    public void save(TbTypeTemplate tbTypeTemplate) {
        tbTypeTemplateMapper.insert(tbTypeTemplate);
    }

    @Override
    public TbTypeTemplate findOne(long id) {
        return tbTypeTemplateMapper.selectByPrimaryKey(id);
    }

    @Autowired
    TbSpecificationOptionMapper tbSpecificationOptionMapper;

    @Override
    public List<Map> findSpecList(long id) {
        TbTypeTemplate typeTemplate = findOne(id);
        //"[{\"id\":27,\"text\":"网络"},{"id":32,"text":"机身内存"}]"
        // List   Map  {key:id   value: 27 ,key text : 网络}{key:id   value: 27 ,key text : 网络}
        List<Map> maps = JSON.parseArray(typeTemplate.getSpecIds(), Map.class);
        if(maps!=null&&maps.size()>0){
            for(Map spec : maps){
                //循环遍历每一个规格
                //根据id  查询出对应的规格选项
                TbSpecificationOptionExample optionExample = new TbSpecificationOptionExample();
                optionExample.createCriteria().andSpecIdEqualTo(Long.parseLong(spec.get("id").toString()));
                List<TbSpecificationOption> optionList = tbSpecificationOptionMapper.selectByExample(optionExample);
                spec.put("options",optionList);
            }
        }
        return maps;
    }
}
